#!ruby
require 'xmlrpc/client'
require 'csv'
require 'pp'

# Wiki tokens...               
imageMacro      = "[[Image(${url})]]\n\n"
sourceStubPath  = "source:/flexdev/project/trunk/build/flex/src"
imageSourcePath = "source:/flexdev/sandbox/ui_alpha/UiComponentCyclopedia/_images/"

# template tokens
urlToken        = "${url}"
componentToken  = "${component.name}"
sourceToken     = "${source.class}"
asdocToken      = "${asdoc.url}"
imagesToken     = "${images}"

def setupTracServer (url, user, password)
  # Init tracServer client 
  tracServer = XMLRPC::Client.new2(url)
  tracServer.user = user
  tracServer.password = password  
  return tracServer
end

def getTemplatePage (tracWikiPages, tracServer)
  # wiki page vars   
  templateResults = <<`EOC`
  CocoaDialog dropdown \
    --title "UI Cyclopedia Builder" \
    --text "Select Page Template" \
    --items #{tracWikiPages} --button1 "Select" --button2 "Cancel" --string-output
EOC

  templateResult = templateResults.split("\n")

  if templateResult[0] == "Select"
    templatePage = tracServer.call("wiki.getPage", templateResult[1]) 
    return templatePage
  else
    exit
  end
end

def getImageTemplate(tracWikiPages, tracServer)
  imageTemplateResults = <<`EOC`
  CocoaDialog dropdown \
    --title "UI Cyclopedia Builder" \
    --text "Select Image Section Template" \
    --items #{tracWikiPages} --button1 "Select" --button2 "Cancel" --string-output
EOC
 
  imageTemplateResult = imageTemplateResults.split("\n")

  if imageTemplateResult[0] == "Select"
    imageSectionPage = tracServer.call("wiki.getPage", imageTemplateResult[1]) 
    return imageSectionPage
  else 
    exit
  end  
end

def getCsvFilename()
  listFile = <<`EOC`
  CocoaDialog fileselect \
    --title 'Select CSV file' \
    --text 'Choose a CSV file to generate Trac pages' \
    --with-extensions .csv
EOC
  return listFile.split("\n")[0]  
end

tracServer       = setupTracServer( ENV["TM_TRACURL"], ENV["TM_TRACUSER"], ENV["TM_TRACPASSWORD"] )
pageStruct       = {"author" => ENV["TRAC_USER"]}
tracWikiPages    = tracServer.call("wiki.getAllPages").join(" ")
templatePage     = getTemplatePage(tracWikiPages, tracServer)
imageSectionPage = getTemplatePage(tracWikiPages, tracServer)   

# containedTemplateName = <<`EOC`
# CocoaDialog dropdown --text "Select Contained Section Template" --items #{tracWikiPages} --button1 "Select" --string-output
# EOC
# 
# containedSectionPage = tracServer.call("wiki.getPage", containedTemplateName.split("\n")[1]) 
# puts containedSectionPage


   

# Parse CSV and build pages...                    

print templatePage
CSV.open(getCsvFilename(), 'r') do |row|   
  # get template  
  tempWikiPage = templatePage 
  # replace heading
  tempWikiPage.sub!(componentToken, row[0])
  # replace source path
  tempWikiPage.sub!(sourceToken, "#{sourceStubPath}#{row[1]}")
  # replace asDoc link
  tempWikiPage.sub!(asdocToken, row[2])
  
  count = row[3].data.to_i
  
  # Image section
  if count > 0 then
    # more than 0 images specified...
    
    # Get image section template 
    tempImageSection = tracServer.call("wiki.getPage", imageTemplateResult[1])
    
    # Loop number of images...
    count.times do |n|
      # Append Image() macros to the Image Section Template
      tempImageSection << imageMacro.sub(urlToken, "#{imageSourcePath}#{row[0]}_#{n+1}.png" )      
    end                                                                                      
    
    # Add image section to the template
    tempWikiPage.sub!(imagesToken, tempImageSection)
  else
    # otherwise remove the image section token from the page.
    tempWikiPage.sub!(imagesToken, '')
  end                                                        
    
  tracServer.call("wiki.putPage", row[0], tempWikiPage, pageStruct) 
  
  # Debug message
  # print "\n#{tempWikiPage}\n"
end                     


